package controller;

import model.User;
import services.UserService;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private final UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random(System.currentTimeMillis());
        StringBuilder sb = new StringBuilder();

        char sc = 'a';
        for (int i = 0; i <= 4; i++) {
            int str = random.nextInt(62);
            if (str < 10) {
                sb.append(str);
            } else if (str < 36) {
                sc = (char) ((str - 10) + 'a');
                sb.append(sc);
            } else {
                sc = (char) ((str - 36) + 'A');
                sb.append(sc);
            }
        }

        BufferedImage image = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.GRAY);
        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
        graphics.setColor(Color.blue);
        graphics.setFont(new Font("Time", Font.BOLD, 18));
        graphics.drawString(sb.toString(), 3, 17);
        graphics.dispose();
        ImageIO.write(image, "JPG", response.getOutputStream());
        System.out.println("生成的验证码：" + sb.toString());
        HttpSession session = request.getSession();
        session.setAttribute("vaildCode", sb.toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String remember = request.getParameter("remember");
        System.out.println("输入的用户名：" + username);
        System.out.println("输入的密码：" + password);
        System.out.println("输入的验证码：" + vcode);

        String msg = null;
        HttpSession session = request.getSession();
        String validcode = (String) session.getAttribute("vaildCode");
        System.out.println("session中存储的验证码：" + validcode);
        if (!validcode.equals(vcode)) {
            msg = "验证码错误";
        }
        User user = userService.doLogin(username, password);
        System.out.println(user);
        if (user == null) {
            msg = "用户名不存在，请注册！";
            System.out.println("用户不存在！");

        } else {
            if (!user.getPassword().equals(password)) {
                msg = "密码错误！";
                System.out.println("密码错误！");
            }
        }
        if (msg == null) {
            String contextPath = request.getContextPath();
            session.setAttribute("user", user);
            // 记住密码
            if ("1".equals(remember)) {
                System.out.println("生成cookie");
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", password);

                usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                passwordCookie.setMaxAge(60 * 60 * 24 * 7);

                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }
            response.sendRedirect(contextPath + "/index.jsp");
        } else {
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }
}
